#include    <InputFileReader.h>

#include    <iostream>
#include    <fstream>

using   std::ifstream;
using   std::string;

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
InputFileReader::InputFileReader() :
    init(false) 
{ 
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
InputFileReader::~InputFileReader()
{ 
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Status InputFileReader::Init(const char *filename)
{
    ifstream f(filename);

    if (!f.is_open()) {
        std::cerr << "ERROR: file not found: " << filename << std::endl;
        return ERROR;
    }

    unsigned int lineNum = 0;

    while (!f.eof()) {
        string            line;
        string::size_type offset;
        char              *whitespace = " \n\t\r";

        getline(f, line);

        lineNum++;

        // truncate line at comment
        if ((offset = line.find_first_of("#")) != string::npos)
            line.erase(offset);
        // trim leading/trailing whitespace
        line.erase(0, line.find_first_not_of(whitespace));
        line.erase(line.find_last_not_of(whitespace) + 1);
        if (line.size() == 0)
            continue;

        // parse key/value fields and add to config map container
        if ((offset = line.find_first_of(whitespace)) != string::npos) {
            string key(line, 0, offset);
            string val(line, offset, line.size() - offset);
            val.erase(0, val.find_first_not_of(whitespace));
            if (key.size() && val.size()) {
                inputMap[key] = val;
                continue;
            }
        }

        std::cerr << "ERROR: File " << filename << " at line " << lineNum <<
            ": bad string '" << line.c_str() << "'\n";
        f.close();
        return ERROR;
    }

    f.close();

    init = true;

    return AOK;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Status InputFileReader::Get(const char *key, string& val)
{
    if (!init)
        return ERROR;

    val = inputMap[key];

    return (val.empty() ? ERROR : AOK);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Status InputFileReader::Get(const char *key, Real& val)
{
    string  tmpString;

    if (!Get(key, tmpString))
        return ERROR;

    val = strtod(tmpString.c_str(), 0);

    return AOK;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// eof
